import React, {useEffect, useRef, useState} from "react";
import {Button, Select} from "antd";
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormInstance,
  ProFormList,
  ProFormMoney,
  ProFormSelect, ProFormSwitch, ProFormText
} from "@ant-design/pro-form";
import {PlusOutlined} from "@ant-design/icons";


import {useMount, useRequest} from "ahooks";

import {ProFormTextArea} from "@ant-design/pro-components";
import {findByFindOrderList} from "@/services/ant-design-pro/goods";
import {serachMiniByPhone} from "@/services/ant-design-pro/users";
import {createBackOrder} from "@/services/ant-design-pro/order";

interface Props {
  type:number | 0;
  row?: API.TaoCanMaster,
  onSuccess?: () => void;
}

const EditOrderDialog: React.FC<Props> = (props) => {
  const { row, onSuccess,type = 0} = props
  const [userId, setUserId] = useState<number> ( 0 );

  const formRef = useRef<ProFormInstance> ();
  // @ts-ignore
  const {
    runAsync: fetchByList,
  } = useRequest ( findByFindOrderList, {
    debounceWait: 100,
    manual: true,
  } );

  useEffect ( () => {
    if(userId>0) {
      fetchByList ( {userId: userId} ).then ( res => {
        let data = res?.data;
        getSuanGoods ( data );
        //  formRef.set("goods",data)
        // formRef.current?.setFieldValue ( "goods", data );
      } )
    }
  }, [userId] );


  useMount ( () => {

  } )
  const handleSearch = (newValue: string) => {
    //fetch(newValue, setData);
  };

  const handleChange = (newValue: string) => {
    //  setValue(newValue);
  };

  // @ts-ignore
  const getSuanGoods = (fieldValue: [API.GoodsTaoCan] = []) => {
    if (fieldValue.length > 0) {
      let paymentAmount = 0;
      let totalAmount = 0;
      let discountAmount = 0;
      let quantity = 0;
      // @ts-ignore
      let newValue: [API.GoodsTaoCan] = []
      for (let i = 0; i < fieldValue.length; i++) {
        let goodsTaoCan = fieldValue[i];
        quantity = quantity + (goodsTaoCan.quantity ? goodsTaoCan.quantity : 0);
        goodsTaoCan.quantity = goodsTaoCan.quantity ? goodsTaoCan.quantity : 0;
        goodsTaoCan.paymentAmount = (goodsTaoCan.quantity * goodsTaoCan.price)
        goodsTaoCan.totalAmount = (goodsTaoCan.quantity * goodsTaoCan.totalAmountL)
    //    goodsTaoCan.price =goodsTaoCan.totalAmountL
        goodsTaoCan.discountAmount = (goodsTaoCan.quantity * goodsTaoCan.discountAmountL)
        paymentAmount = paymentAmount + goodsTaoCan.paymentAmount;
        totalAmount = totalAmount + goodsTaoCan.totalAmount;
        discountAmount = discountAmount + goodsTaoCan.discountAmount;
        newValue.push ( goodsTaoCan );
      }
      if (formRef.current != undefined) {
// @ts-ignore
        formRef.current.setFieldValue ( "goods", newValue );
        formRef.current.setFieldValue ( "cloudType", type );
        formRef.current.setFieldValue ( "totalAmount", totalAmount );
        formRef.current.setFieldValue ( "paymentAmount", paymentAmount );
        formRef.current.setFieldValue ( "price", paymentAmount );

        formRef.current.setFieldValue ( "discountAmount", discountAmount );
        formRef.current.setFieldValue ( "quantity", quantity );
       // console.log ( newValue )
      }
    }
  }

  return (
    <ModalForm<API.TaoCanMaster>
      width={1000}
      initialValues={row}
      formRef={formRef}
      title="新建表单"
      trigger={
        <Button ghost type="primary">
          <PlusOutlined/>
          {'添加套餐'}
        </Button>
      }
      onVisibleChange={(b) => {
        if (b) {
          setTimeout ( () => {
            //setAgent ( taocanId )
          }, 1000 )

        }
      }}

      onValuesChange={((value) => {
        let fieldValue: [API.GoodsTaoCan] = formRef.current?.getFieldValue ( "goods" );
        getSuanGoods ( fieldValue );

      })} onFinish={(val) => {

      val.userId=val?.userId?.value;
      val.cloudType=type;

      console.log ("VVVVVVVVVVVVVVVV",val)
  return new Promise<boolean> ( (resolve, reject) => {
        createBackOrder ( val ).then ( res => {
          if (onSuccess) {
            onSuccess ()
          }
          resolve ( true )
        } ).catch ( e => {
          reject ( false )
        } )
      } )
    }}>

      <ProForm.Group size={10} spaceProps={{size: 10}} grid={true} labelLayout={"inline"}>
        <ProFormSelect.SearchSelect
allowClear={true}
name="userId"
required={true}
mode={"single"}
rules={[{
  required:true
}]}
          showSearch={true}
 width="sm"
label="用户选择"

 request={serachMiniByPhone}
onChange={(value)=>{
  console.log(value)
  setUserId(value?.id)
}}
fieldProps={{
  optionItemRender:((option)=>{
    return (option?.name?option?.name:'没有')+"-"+option?.label
  })
}}




        />

        <ProFormMoney
          width="sm"
          name="paymentAmount"
          label="支付金额"
          disabled={true}

required={true}

          placeholder="请输入名称"
        />

        <ProFormMoney
          width="sm"
          name="discountAmount"
          label="优惠金额"
          placeholder="请输入名称"
          disabled={true}
        />
        <ProFormMoney
          width="sm"
          name="totalAmount"
          label="总额"
          placeholder="请输入名称"
          disabled={true}
        />
        <ProFormText
          width="sm"
          name="quantity"
          label="总数"
          placeholder="0"
          disabled={true}
        />
  {/*      <ProFormSelect
          width="sm"
          name="cloudType"

          label="云库存"
          placeholder="0"
          options={[
            {
              value: 0,
              label: '本地库存'
            },
            {
              value: 1,
              label: '云库存'
            },
          ]}

        />*/}
      </ProForm.Group>
      <ProForm.Group>

        <ProFormTextArea
          width="md"
          name="remark"
          label="备注"
          placeholder="请输入备注"

        />
      </ProForm.Group>
      <ProFormList
        name="goods"
        copyIconProps={false}
        deleteIconProps={false} creatorButtonProps={false}>
        {(f, index, action) => {
         // console.log ( f )
          let currentRowData = action.getCurrentRowData ();
          let total = (currentRowData.price * currentRowData.quantity)
       //   console.log ( currentRowData, total )
          /*     action.setCurrentRowData({
                  paymentAmount: (currentRowData.price*currentRowData.quantity)
                //  remark: undefined,
                });*/
          return (<ProForm.Group grid={true} labelLayout={"inline"}>
              <ProFormText
                width="sm"
                name="name"
                label="商品名称"
                disabled={true}

                placeholder="请输入名称"
              />

              <ProFormMoney
                disabled={true}
                width="sm"
                name="price"
                label="价格"
                placeholder="请输入名称"
              />
              <ProFormMoney
                disabled={true}
                width="sm"
                name="paymentAmount"

                label="总价格"

                placeholder="请输入名称"
              />

              <ProFormDigit
                width="sm"
                name="quantity"
                label="个数"
                placeholder="请输入名称"

              />
            </ProForm.Group>
          );
        }}
      </ProFormList>
    </ModalForm>

  )
}

export default EditOrderDialog;
